package com.nti56.springboot.utils;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;
 
public class FileUtil {
	
	//静态方法：三个参数：文件的二进制，文件路径，文件名
	//通过该方法将在指定目录下添加指定文件	
	public static void fileupload(byte[] file,String filePath,String fileName) throws IOException {
		//目标目录		
		File targetfile = new File(filePath);
		if(!targetfile.exists()) {
			targetfile.mkdirs();
		}
		//二进制流写入		
		FileOutputStream out = new FileOutputStream(filePath+"/"+fileName);
	    out.write(file);
	    out.flush();
	    out.close();
	}
	
	 /**
     * 删除单个文件
     *
     * @param fileName
     *            要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }
    
    public static boolean download(HttpServletResponse response,String filePath,String fileName){
    	 File file = new File(filePath + fileName);
    	 if(file.exists()){ //判断文件父目录是否存在
             response.setContentType("application/force-download");
             response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
             byte[] buffer = new byte[1024];
             FileInputStream fis = null; //文件输入流
             BufferedInputStream bis = null;
             OutputStream os = null; //输出流
             try {
                 os = response.getOutputStream();
                 fis = new FileInputStream(file); 
                 bis = new BufferedInputStream(fis);
                 int i = bis.read(buffer);
                 while(i != -1){
                     os.write(buffer);
                     i = bis.read(buffer);
                 }
             } catch (Exception e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
             System.out.println("----------file download: " + fileName);
             try {
                 bis.close();
                 fis.close();
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
                 return false;
             }
         }
         return true;
     }

}